package GUI;

import util.User;
import util.DatabaseUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import java.awt.geom.Ellipse2D;
import java.util.HashMap;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.awt.geom.Point2D;

/**
 * 绿色出行信息面板，用于显示出行线路和共享交通工具信息
 */
public class RouteInfoPanel extends JPanel {
    private User currentUser;
    private JTabbedPane subTabPane;
    private JTable routesTable;
    private JTable vehiclesTable;
    private JTextArea newsTextArea;
    private JPanel newsPanel;
    private Timer newsTimer;
    private List<String> newsList;
    private int currentNewsIndex = 0;

    // 共享交通工具地图视图
    private MapPanel mapPanel;
    private JPanel vehiclesCardPanel;
    private CardLayout vehiclesCardLayout;
    private JLabel statusLabel;
    private Timer refreshTimer;
    private Map<String, Color> vehicleTypeColors = new HashMap<>();

    public RouteInfoPanel(User user) {
        this.currentUser = user;

        // 初始化交通工具类型颜色
        vehicleTypeColors.put("共享单车", new Color(52, 152, 219)); // 蓝色
        vehicleTypeColors.put("共享电动车", new Color(46, 204, 113)); // 绿色

        // 设置布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建子标签页面板
        subTabPane = new JTabbedPane();

        // 创建出行线路标签页
        JPanel routesPanel = createRoutesPanel();
        subTabPane.addTab("出行线路", routesPanel);

        // 创建共享交通工具标签页
        JPanel vehiclesPanel = createVehiclesPanel();
        subTabPane.addTab("共享交通工具", vehiclesPanel);

        // 添加子标签页面板到主面板
        add(subTabPane, BorderLayout.CENTER);

        // 创建资讯面板
        newsPanel = createNewsPanel();
        add(newsPanel, BorderLayout.SOUTH);

        // 加载数据
        loadRoutesData();
        loadVehiclesData();
        loadNewsData();

        // 设置自动刷新定时器
        refreshTimer = new Timer(60000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 每分钟刷新一次共享交通工具数据
                if (subTabPane.getSelectedIndex() == 1) {
                    loadVehiclesData();
                    statusLabel.setText("数据已更新: " + new SimpleDateFormat("HH:mm:ss").format(new java.util.Date()));
                }
            }
        });
        refreshTimer.start();
    }

    /**
     * 创建出行线路面板
     */
    private JPanel createRoutesPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };

        // 添加列
        model.addColumn("线路类型");
        model.addColumn("线路名称");
        model.addColumn("起点站");
        model.addColumn("终点站");
        model.addColumn("途经站点");
        model.addColumn("预计时间(分钟)");

        // 创建表格
        routesTable = new JTable(model);
        routesTable.getTableHeader().setReorderingAllowed(false);
        routesTable.setRowHeight(25);

        // 创建滚动面板并添加表格
        JScrollPane scrollPane = new JScrollPane(routesTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 创建筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        JLabel typeLabel = new JLabel("线路类型:");
        String[] typeOptions = { "全部", "公交", "地铁" };
        JComboBox<String> typeComboBox = new JComboBox<>(typeOptions);

        JLabel regionLabel = new JLabel("地区:");
        JTextField regionField = new JTextField(10);
        regionField.setText(currentUser.getRegion()); // 默认显示用户所在地区

        JButton filterButton = new JButton("筛选");
        filterButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String type = (String) typeComboBox.getSelectedItem();
                String region = regionField.getText();
                loadRoutesData(type, region);
            }
        });

        filterPanel.add(typeLabel);
        filterPanel.add(typeComboBox);
        filterPanel.add(regionLabel);
        filterPanel.add(regionField);
        filterPanel.add(filterButton);

        panel.add(filterPanel, BorderLayout.NORTH);

        return panel;
    }

    /**
     * 创建共享交通工具面板
     */
    private JPanel createVehiclesPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 使用卡片布局切换表格视图和地图视图
        vehiclesCardPanel = new JPanel();
        vehiclesCardLayout = new CardLayout();
        vehiclesCardPanel.setLayout(vehiclesCardLayout);

        // 表格视图
        JPanel tableViewPanel = createVehiclesTablePanel();
        vehiclesCardPanel.add(tableViewPanel, "table");

        // 地图视图
        JPanel mapViewPanel = createVehiclesMapPanel();
        vehiclesCardPanel.add(mapViewPanel, "map");

        // 默认显示表格视图
        vehiclesCardLayout.show(vehiclesCardPanel, "table");

        // 创建视图切换和筛选面板
        JPanel controlPanel = new JPanel(new BorderLayout());

        // 筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        JLabel typeLabel = new JLabel("交通工具类型:");
        String[] typeOptions = { "全部", "共享单车", "共享电动车" };
        JComboBox<String> typeComboBox = new JComboBox<>(typeOptions);

        JLabel regionLabel = new JLabel("地区:");
        JTextField regionField = new JTextField(10);
        regionField.setText(currentUser.getRegion()); // 默认显示用户所在地区

        JButton filterButton = new JButton("筛选");
        filterButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String type = (String) typeComboBox.getSelectedItem();
                String region = regionField.getText();
                loadVehiclesData(type, region);
            }
        });

        filterPanel.add(typeLabel);
        filterPanel.add(typeComboBox);
        filterPanel.add(regionLabel);
        filterPanel.add(regionField);
        filterPanel.add(filterButton);

        // 视图切换面板
        JPanel viewPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        ButtonGroup viewButtonGroup = new ButtonGroup();
        JRadioButton tableViewButton = new JRadioButton("表格视图", true);
        JRadioButton mapViewButton = new JRadioButton("地图视图");

        // 添加视图切换逻辑
        tableViewButton.addActionListener(e -> vehiclesCardLayout.show(vehiclesCardPanel, "table"));
        mapViewButton.addActionListener(e -> vehiclesCardLayout.show(vehiclesCardPanel, "map"));

        viewButtonGroup.add(tableViewButton);
        viewButtonGroup.add(mapViewButton);

        viewPanel.add(tableViewButton);
        viewPanel.add(mapViewButton);

        // 添加刷新按钮
        JButton refreshButton = new JButton("刷新数据");
        refreshButton.addActionListener(e -> {
            loadVehiclesData();
            statusLabel.setText("数据已更新: " + new SimpleDateFormat("HH:mm:ss").format(new java.util.Date()));
        });
        viewPanel.add(refreshButton);

        // 状态标签
        statusLabel = new JLabel("数据已就绪");
        statusLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));

        // 组合控制面板
        controlPanel.add(filterPanel, BorderLayout.WEST);
        controlPanel.add(viewPanel, BorderLayout.EAST);

        // 添加到主面板
        panel.add(controlPanel, BorderLayout.NORTH);
        panel.add(vehiclesCardPanel, BorderLayout.CENTER);
        panel.add(statusLabel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 创建共享交通工具表格面板
     */
    private JPanel createVehiclesTablePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };

        // 添加列
        model.addColumn("交通工具类型");
        model.addColumn("位置");
        model.addColumn("地区");
        model.addColumn("可用数量");
        model.addColumn("状态");
        model.addColumn("最后更新时间");

        // 创建表格
        vehiclesTable = new JTable(model);
        vehiclesTable.getTableHeader().setReorderingAllowed(false);
        vehiclesTable.setRowHeight(25);

        // 表格行渲染器
        vehiclesTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

                // 根据状态列显示不同颜色
                if (column == 4) {
                    if ("充足".equals(value)) {
                        c.setForeground(new Color(46, 204, 113)); // 绿色
                    } else if ("较少".equals(value)) {
                        c.setForeground(new Color(243, 156, 18)); // 橙色
                    } else if ("紧缺".equals(value)) {
                        c.setForeground(new Color(231, 76, 60)); // 红色
                    } else {
                        c.setForeground(table.getForeground());
                    }
                } else {
                    // 其他列使用默认颜色
                    c.setForeground(table.getForeground());
                }

                return c;
            }
        });

        // 创建滚动面板并添加表格
        JScrollPane scrollPane = new JScrollPane(vehiclesTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 创建共享交通工具地图视图面板
     */
    private JPanel createVehiclesMapPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建地图面板
        mapPanel = new MapPanel();
        panel.add(mapPanel, BorderLayout.CENTER);

        // 创建图例面板
        JPanel legendPanel = new JPanel();
        legendPanel.setBorder(BorderFactory.createTitledBorder("图例"));

        for (Map.Entry<String, Color> entry : vehicleTypeColors.entrySet()) {
            JLabel colorBox = new JLabel("   ");
            colorBox.setOpaque(true);
            colorBox.setBackground(entry.getValue());
            colorBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));

            legendPanel.add(colorBox);
            legendPanel.add(new JLabel(entry.getKey()));
            legendPanel.add(Box.createHorizontalStrut(15));
        }

        // 添加状态图例
        JLabel greenDot = new JLabel(" ● ");
        greenDot.setForeground(new Color(46, 204, 113));
        legendPanel.add(greenDot);
        legendPanel.add(new JLabel("充足"));
        legendPanel.add(Box.createHorizontalStrut(5));

        JLabel yellowDot = new JLabel(" ● ");
        yellowDot.setForeground(new Color(243, 156, 18));
        legendPanel.add(yellowDot);
        legendPanel.add(new JLabel("较少"));
        legendPanel.add(Box.createHorizontalStrut(5));

        JLabel redDot = new JLabel(" ● ");
        redDot.setForeground(new Color(231, 76, 60));
        legendPanel.add(redDot);
        legendPanel.add(new JLabel("紧缺"));

        panel.add(legendPanel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 创建资讯面板
     */
    private JPanel createNewsPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder("绿色出行资讯"));

        newsTextArea = new JTextArea(3, 50);
        newsTextArea.setLineWrap(true);
        newsTextArea.setWrapStyleWord(true);
        newsTextArea.setEditable(false);
        newsTextArea.setBackground(new Color(240, 240, 240));
        newsTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        JScrollPane scrollPane = new JScrollPane(newsTextArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 加载出行线路数据
     */
    private void loadRoutesData() {
        loadRoutesData("全部", currentUser.getRegion());
    }

    /**
     * 加载筛选后的出行线路数据
     */
    private void loadRoutesData(String type, String region) {
        DefaultTableModel model = (DefaultTableModel) routesTable.getModel();
        model.setRowCount(0); // 清空表格数据

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            StringBuilder sql = new StringBuilder("SELECT * FROM travel_routes WHERE 1=1");

            if (!"全部".equals(type)) {
                sql.append(" AND route_type = ?");
            }

            if (region != null && !region.isEmpty()) {
                sql.append(" AND region = ?");
            }

            pstmt = conn.prepareStatement(sql.toString());

            int paramIndex = 1;

            if (!"全部".equals(type)) {
                pstmt.setString(paramIndex++, type);
            }

            if (region != null && !region.isEmpty()) {
                pstmt.setString(paramIndex, region);
            }

            rs = pstmt.executeQuery();

            while (rs.next()) {
                model.addRow(new Object[] {
                        rs.getString("route_type"),
                        rs.getString("route_name"),
                        rs.getString("start_station"),
                        rs.getString("end_station"),
                        rs.getString("via_stations"),
                        rs.getInt("estimated_time")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this,
                    "加载出行线路数据时发生错误: " + e.getMessage(),
                    "数据库错误",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(this,
                    "数据库驱动加载失败: " + e.getMessage(),
                    "驱动错误",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 加载共享交通工具数据
     */
    private void loadVehiclesData() {
        loadVehiclesData("全部", currentUser.getRegion());
    }

    /**
     * 加载筛选后的共享交通工具数据
     */
    private void loadVehiclesData(String type, String region) {
        DefaultTableModel model = (DefaultTableModel) vehiclesTable.getModel();
        model.setRowCount(0); // 清空表格数据

        // 清空地图数据
        mapPanel.clearVehicleData();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();

            StringBuilder sql = new StringBuilder("SELECT * FROM shared_vehicles WHERE 1=1");

            if (!"全部".equals(type)) {
                sql.append(" AND vehicle_type = ?");
            }

            if (region != null && !region.isEmpty()) {
                sql.append(" AND region = ?");
            }

            pstmt = conn.prepareStatement(sql.toString());

            int paramIndex = 1;

            if (!"全部".equals(type)) {
                pstmt.setString(paramIndex++, type);
            }

            if (region != null && !region.isEmpty()) {
                pstmt.setString(paramIndex, region);
            }

            rs = pstmt.executeQuery();

            while (rs.next()) {
                String vehicleType = rs.getString("vehicle_type");
                String location = rs.getString("location");
                String regionName = rs.getString("region");
                int availableCount = rs.getInt("available_count");
                Timestamp lastUpdate = rs.getTimestamp("last_update");

                // 根据可用数量确定状态
                String status;
                Color statusColor;
                if (availableCount > 10) {
                    status = "充足";
                    statusColor = new Color(46, 204, 113); // 绿色
                } else if (availableCount > 3) {
                    status = "较少";
                    statusColor = new Color(243, 156, 18); // 橙色
                } else {
                    status = "紧缺";
                    statusColor = new Color(231, 76, 60); // 红色
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // 添加到表格
                model.addRow(new Object[] {
                        vehicleType,
                        location,
                        regionName,
                        availableCount,
                        status,
                        dateFormat.format(lastUpdate)
                });

                // 添加到地图
                // 随机位置是为了演示，实际应用中应该使用真实经纬度
                double x = Math.random() * 0.8 + 0.1; // 0.1 到 0.9 之间
                double y = Math.random() * 0.8 + 0.1; // 0.1 到 0.9 之间

                mapPanel.addVehicle(vehicleType, location, x, y, availableCount,
                        vehicleTypeColors.get(vehicleType), statusColor);
            }

            // 更新地图
            mapPanel.repaint();

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this,
                    "加载共享交通工具数据时发生错误: " + e.getMessage(),
                    "数据库错误",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(this,
                    "数据库驱动加载失败: " + e.getMessage(),
                    "驱动错误",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 加载资讯数据
     */
    private void loadNewsData() {
        // 获取资讯数据
        newsList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();
            String sql = "SELECT * FROM travel_news ORDER BY publish_date DESC LIMIT 10";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                String title = rs.getString("title");
                String content = rs.getString("content");
                Date publishDate = rs.getDate("publish_date");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

                newsList.add(dateFormat.format(publishDate) + "  " + title + ": " + content);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(this,
                    "数据库驱动加载失败: " + e.getMessage(),
                    "驱动错误",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }

        // 如果没有数据，添加一些默认的资讯
        if (newsList.isEmpty()) {
            newsList.add("欢迎使用绿色出行系统，目前没有最新资讯。");
        }

        // 显示第一条资讯
        if (!newsList.isEmpty()) {
            newsTextArea.setText(newsList.get(0));
            currentNewsIndex = 0;
        }

        // 设置定时器，每5秒滚动显示一条资讯
        if (newsTimer != null) {
            newsTimer.stop();
        }

        newsTimer = new Timer(5000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 显示下一条资讯
                currentNewsIndex = (currentNewsIndex + 1) % newsList.size();
                newsTextArea.setText(newsList.get(currentNewsIndex));
            }
        });
        newsTimer.start();
    }

    /**
     * 地图面板类 - 用于显示共享交通工具的地图视图
     */
    class MapPanel extends JPanel {
        private List<VehicleMarker> vehicles = new ArrayList<>();
        private String currentRegion;
        private List<TransportStation> stations = new ArrayList<>();
        private List<TransportRoute> routes = new ArrayList<>();
        private boolean showGrid = true;
        private int gridSize = 50;
        private JTable mapTable;
        private DefaultTableModel mapTableModel;
        private static final int MAP_GRID_ROWS = 10;
        private static final int MAP_GRID_COLS = 10;

        public MapPanel() {
            setBackground(Color.WHITE);
            setBorder(BorderFactory.createLineBorder(Color.GRAY));
            currentRegion = currentUser.getRegion();

            // 创建地图网格表格
            setLayout(new BorderLayout());

            // 创建表格模型
            mapTableModel = new DefaultTableModel(MAP_GRID_ROWS, MAP_GRID_COLS) {
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };

            // 创建表格
            mapTable = new JTable(mapTableModel);
            mapTable.setDefaultRenderer(Object.class, new MapCellRenderer());
            mapTable.setRowHeight(50);
            mapTable.setIntercellSpacing(new Dimension(0, 0));
            mapTable.setShowGrid(showGrid);
            mapTable.setGridColor(new Color(200, 200, 200));

            // 调整列宽
            for (int i = 0; i < mapTable.getColumnCount(); i++) {
                mapTable.getColumnModel().getColumn(i).setWidth(50);
                mapTable.getColumnModel().getColumn(i).setMinWidth(50);
                mapTable.getColumnModel().getColumn(i).setMaxWidth(50);
            }

            // 取消表头显示
            mapTable.setTableHeader(null);

            // 添加表格到面板
            JScrollPane scrollPane = new JScrollPane(mapTable);
            scrollPane.setBorder(BorderFactory.createEmptyBorder());
            add(scrollPane, BorderLayout.CENTER);

            // 加载示例站点数据
            loadSampleStations();
        }

        /**
         * 加载示例站点数据
         */
        private void loadSampleStations() {
            // 添加一些示例公交站点
            addStation("公交站", "西直门公交站", 0.2, 0.3, new Color(52, 152, 219));
            addStation("公交站", "北京站公交站", 0.5, 0.6, new Color(52, 152, 219));
            addStation("公交站", "中关村公交站", 0.7, 0.2, new Color(52, 152, 219));

            // 添加一些示例地铁站点
            addStation("地铁站", "西直门地铁站", 0.2, 0.31, new Color(231, 76, 60));
            addStation("地铁站", "北京站地铁站", 0.5, 0.61, new Color(231, 76, 60));
            addStation("地铁站", "中关村地铁站", 0.7, 0.21, new Color(231, 76, 60));

            // 添加示例路线
            addRoute("地铁2号线", new Color(52, 152, 219), new Point2D[] {
                    new Point2D.Double(0.2, 0.31),
                    new Point2D.Double(0.5, 0.61)
            });

            addRoute("公交405路", new Color(46, 204, 113), new Point2D[] {
                    new Point2D.Double(0.2, 0.3),
                    new Point2D.Double(0.5, 0.6),
                    new Point2D.Double(0.7, 0.2)
            });
        }

        public void clearVehicleData() {
            vehicles.clear();
        }

        public void addVehicle(String type, String location, double x, double y, int count,
                Color typeColor, Color statusColor) {
            vehicles.add(new VehicleMarker(type, location, x, y, count, typeColor, statusColor));
            updateTableCell((int) (y * MAP_GRID_ROWS), (int) (x * MAP_GRID_COLS));
        }

        public void addStation(String type, String name, double x, double y, Color color) {
            stations.add(new TransportStation(type, name, x, y, color));
            updateTableCell((int) (y * MAP_GRID_ROWS), (int) (x * MAP_GRID_COLS));
        }

        public void addRoute(String name, Color color, Point2D[] points) {
            routes.add(new TransportRoute(name, color, points));
            // 更新路线经过的表格单元格
            for (Point2D p : points) {
                updateTableCell((int) (p.getY() * MAP_GRID_ROWS), (int) (p.getX() * MAP_GRID_COLS));
            }
        }

        private void updateTableCell(int row, int col) {
            if (row >= 0 && row < MAP_GRID_ROWS && col >= 0 && col < MAP_GRID_COLS) {
                mapTableModel.setValueAt("updated", row, col);
                mapTable.repaint();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int width = getWidth();
            int height = getHeight();

            // 绘制地图背景
            g2d.setColor(new Color(240, 240, 240));
            g2d.fillRect(0, 0, width, height);

            // 绘制网格线
            if (showGrid) {
                g2d.setColor(new Color(220, 220, 220));
                for (int i = 0; i < width; i += gridSize) {
                    g2d.drawLine(i, 0, i, height);
                }
                for (int i = 0; i < height; i += gridSize) {
                    g2d.drawLine(0, i, width, i);
                }
            }

            // 绘制地区名称
            g2d.setColor(Color.DARK_GRAY);
            g2d.setFont(new Font("微软雅黑", Font.BOLD, 18));
            String regionText = currentRegion + " 地区";
            int textWidth = g2d.getFontMetrics().stringWidth(regionText);
            g2d.drawString(regionText, (width - textWidth) / 2, 30);

            // 绘制路线
            for (TransportRoute route : routes) {
                if (route.points.length < 2)
                    continue;

                g2d.setColor(route.color);
                g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

                for (int i = 0; i < route.points.length - 1; i++) {
                    int x1 = (int) (route.points[i].getX() * width);
                    int y1 = (int) (route.points[i].getY() * height);
                    int x2 = (int) (route.points[i + 1].getX() * width);
                    int y2 = (int) (route.points[i + 1].getY() * height);

                    g2d.drawLine(x1, y1, x2, y2);
                }

                // 绘制路线名称
                Point2D midPoint = route.points[route.points.length / 2];
                int midX = (int) (midPoint.getX() * width);
                int midY = (int) (midPoint.getY() * height) - 10;

                g2d.setFont(new Font("微软雅黑", Font.BOLD, 11));
                g2d.setColor(route.color.darker());
                g2d.drawString(route.name, midX, midY);
            }

            // 绘制站点标记
            for (TransportStation station : stations) {
                int x = (int) (station.x * width);
                int y = (int) (station.y * height);

                // 绘制站点符号
                g2d.setColor(station.color);
                if (station.type.equals("地铁站")) {
                    // 地铁站使用方形标记
                    g2d.fillRect(x - 8, y - 8, 16, 16);
                    g2d.setColor(Color.WHITE);
                    g2d.setFont(new Font("微软雅黑", Font.BOLD, 10));
                    g2d.drawString("M", x - 5, y + 4);
                } else {
                    // 公交站使用圆形标记
                    g2d.fillOval(x - 8, y - 8, 16, 16);
                    g2d.setColor(Color.WHITE);
                    g2d.setFont(new Font("微软雅黑", Font.BOLD, 10));
                    g2d.drawString("B", x - 4, y + 4);
                }

                // 绘制站点名称
                g2d.setColor(Color.BLACK);
                g2d.setFont(new Font("微软雅黑", Font.PLAIN, 11));
                g2d.drawString(station.name, x - g2d.getFontMetrics().stringWidth(station.name) / 2, y + 25);
            }

            // 绘制交通工具标记
            for (VehicleMarker marker : vehicles) {
                int x = (int) (marker.x * width);
                int y = (int) (marker.y * height);

                // 绘制标记背景
                g2d.setColor(marker.typeColor);
                Ellipse2D circle = new Ellipse2D.Double(x - 15, y - 15, 30, 30);
                g2d.fill(circle);

                // 绘制边框
                g2d.setColor(marker.statusColor);
                g2d.setStroke(new BasicStroke(3));
                g2d.draw(circle);

                // 绘制数量
                g2d.setColor(Color.WHITE);
                g2d.setFont(new Font("微软雅黑", Font.BOLD, 12));
                String countText = String.valueOf(marker.count);
                int countWidth = g2d.getFontMetrics().stringWidth(countText);
                g2d.drawString(countText, x - countWidth / 2, y + 5);

                // 绘制位置名称
                g2d.setColor(Color.BLACK);
                g2d.setFont(new Font("微软雅黑", Font.PLAIN, 11));
                g2d.drawString(marker.location, x - g2d.getFontMetrics().stringWidth(marker.location) / 2, y + 30);
            }
        }

        /**
         * 表格单元格渲染器
         */
        class MapCellRenderer extends DefaultTableCellRenderer {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int col) {

                super.getTableCellRendererComponent(table, "", isSelected, hasFocus, row, col);
                setBackground(Color.WHITE);
                setOpaque(true);

                // 查找此单元格区域内的元素
                double cellX = (double) col / MAP_GRID_COLS;
                double cellY = (double) row / MAP_GRID_ROWS;
                double cellWidth = 1.0 / MAP_GRID_COLS;
                double cellHeight = 1.0 / MAP_GRID_ROWS;

                // 检查是否有站点
                for (TransportStation station : stations) {
                    if (station.x >= cellX && station.x < cellX + cellWidth &&
                            station.y >= cellY && station.y < cellY + cellHeight) {
                        setBackground(new Color(station.color.getRed(),
                                station.color.getGreen(),
                                station.color.getBlue(), 60));
                        return this;
                    }
                }

                // 检查是否有交通工具
                for (VehicleMarker marker : vehicles) {
                    if (marker.x >= cellX && marker.x < cellX + cellWidth &&
                            marker.y >= cellY && marker.y < cellY + cellHeight) {
                        setBackground(new Color(marker.typeColor.getRed(),
                                marker.typeColor.getGreen(),
                                marker.typeColor.getBlue(), 60));
                        return this;
                    }
                }

                // 检查是否有路线经过
                for (TransportRoute route : routes) {
                    for (int i = 0; i < route.points.length - 1; i++) {
                        if (lineIntersectsCell(route.points[i].getX(), route.points[i].getY(),
                                route.points[i + 1].getX(), route.points[i + 1].getY(),
                                cellX, cellY, cellWidth, cellHeight)) {
                            setBackground(new Color(route.color.getRed(),
                                    route.color.getGreen(),
                                    route.color.getBlue(), 40));
                            return this;
                        }
                    }
                }

                return this;
            }

            private boolean lineIntersectsCell(double x1, double y1, double x2, double y2,
                    double cellX, double cellY, double cellWidth, double cellHeight) {
                // 简单检查线段是否穿过单元格区域
                double cellX2 = cellX + cellWidth;
                double cellY2 = cellY + cellHeight;

                // 检查线段的两端是否在单元格内
                if ((x1 >= cellX && x1 < cellX2 && y1 >= cellY && y1 < cellY2) ||
                        (x2 >= cellX && x2 < cellX2 && y2 >= cellY && y2 < cellY2)) {
                    return true;
                }

                // 简化的线段与矩形相交检测
                // 实际应用中可使用更精确的算法
                return false;
            }
        }

        /**
         * 共享交通工具标记类
         */
        class VehicleMarker {
            String type;
            String location;
            double x, y;
            int count;
            Color typeColor;
            Color statusColor;

            public VehicleMarker(String type, String location, double x, double y, int count,
                    Color typeColor, Color statusColor) {
                this.type = type;
                this.location = location;
                this.x = x;
                this.y = y;
                this.count = count;
                this.typeColor = typeColor;
                this.statusColor = statusColor;
            }
        }

        /**
         * 交通站点类
         */
        class TransportStation {
            String type;
            String name;
            double x, y;
            Color color;

            public TransportStation(String type, String name, double x, double y, Color color) {
                this.type = type;
                this.name = name;
                this.x = x;
                this.y = y;
                this.color = color;
            }
        }

        /**
         * 交通路线类
         */
        class TransportRoute {
            String name;
            Color color;
            Point2D[] points;

            public TransportRoute(String name, Color color, Point2D[] points) {
                this.name = name;
                this.color = color;
                this.points = points;
            }
        }
    }
}
